import { onBeforeUnmount, ref } from 'vue';
import { designComponent } from '@/use/designComponent';
import { DemoUseEventTable, DemoUseEventTablePart } from './DemoUseEventTable';

export const DemoUseEventTableHead = designComponent({
  setup() {

    const wrapperEl = ref(null as null | HTMLDivElement);
    const table = DemoUseEventTable.use.inject();

    const handler = {
      /**
       * 组件销毁的时候如果不取消监听事件,则监听事件一直有效
       * 此时wrapperEl节点已经销毁,会导致一直报错
       */
      scroll: (e: Event, part: DemoUseEventTablePart) => {
        if (part === DemoUseEventTablePart.body) {
          wrapperEl.value!.scrollLeft = (e.target as HTMLDivElement).scrollLeft;
        }
      },
      wrapperScroll: (e: Event) => {
        if (table.state.hoverPart === DemoUseEventTablePart.head) {
          table.event.emit.scroll(e, DemoUseEventTablePart.head);
        }
      },
      mousewheel: (e: MouseWheelEvent) => {
        wrapperEl.value!.scrollLeft = wrapperEl.value!.scrollLeft + e.deltaY;
      }
    }

    table.event.on.scroll(handler.scroll);
    onBeforeUnmount(() => table.event.off.scroll(handler.scroll));

    return {
      render: () => (
        <div
          class='demo-use-event-table-head'
          ref={wrapperEl}
          onScroll={handler.wrapperScroll}
          {...{onMousewheel: handler.mousewheel}}
        >
          <div class="demo-use-event-table-head-inner">
            table head
          </div>
        </div>
      )
    }
  }
})